package com.lxkpt.controller;

import com.lxkpt.util.FtpUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping(value = "/ftp")
public class FtpController {

    @Resource
    private FtpUtil ftpUtil;

    /**
     * ftp上传文件
     *
     * @param file
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Object uploadImg(@RequestParam("file") MultipartFile file) throws IOException {
        Map<Object, Object> map = new HashMap<>();
        String fileName = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        String datePath = dateFormat.format(now);
        Boolean flag = ftpUtil.uploadFile(datePath, fileName, inputStream);
        if (flag == true) {
            map.put("code", 200);
            map.put("path", ftpUtil.FTP_BASEPATH_SERVER + "/" + datePath + "/" + fileName);
        } else {
            map.put("code", 100);
            map.put("msg", "上传文件失败");
        }
        return map;
    }
}